package org.xczy.boot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.xczy.boot.entity.User;
import org.xczy.boot.mapper.UserMapper;
import org.xczy.boot.utils.RedisUtil;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserService {

  @Resource
  private UserMapper userMapper;

  @Resource
  private RedisUtil redisUtil;

  public int addUser(User user) {
    int i;
    try {
      i = userMapper.addUser(user);
    }catch (Exception e){
      i = -1;
    }
    return i;
  }

  public int deleteById(Integer id) {
    return userMapper.deleteById(id);
  }

  public int updateById(User user) {
    user.setCreateTime(new Date()); // todo 有问题暂时这么解决
    user.setUpdateTime(new Date());
    return userMapper.updateById(user);
  }

  public User getUserById(Integer id) {
    User user = userMapper.getUserById(id);
    if(user != null){
      user.setPassword("******");
    }
    return user;
  }

  public List<User> getAllUser() {
    List<User> userList = userMapper.getAllUser();
    if(userList.size() > 0){
      for(User user : userList){
        user.setPassword("******");
      }
    }
    return userList;
  }

  public User login(User user){
    User loginUser = userMapper.login(user);
    if(loginUser == null){
      return null;
    }
    if(redisUtil.getValue(loginUser.getId().toString()) == null){
      redisUtil.setValue(loginUser.getId().toString(),loginUser);
    }
    return loginUser;
  }

}
